#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import logging
from utility.wechat_auth import wechat_auth_service
from cors_middleware import CorsResource
from utility import tools

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class WeChatLoginResource(CorsResource):
    """
    微信登录资源
    处理微信登录请求
    """
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state
        wechat_auth_service.set_cache_client(self.game_state.cache_db)

    def render_POST(self, request):
        """
        处理微信登录请求
        请求参数: code (微信登录凭证)
        """
        try:
            # 解析请求体
            content = request.content.read()
            if content:
                data = json.loads(content)
            else:
                data = {}

            # 获取微信登录凭证code
            code = data.get('code') or request.args.get(b'code', [None])[0]
            if isinstance(code, bytes):
                code = code.decode('utf-8')

            if not code:
                request.setResponseCode(400)
                return json.dumps({
                    "code": 100,
                    "msg": "缺少微信登录凭证code"
                }).encode('utf-8')

            # 调用微信认证服务进行登录
            result = wechat_auth_service.wechat_login(code)
            result = tools.dict_snake_case_to_camel(result)

            # 设置响应
            if result.get("code") == 0:
                request.setResponseCode(200)
            else:
                request.setResponseCode(401)

            return json.dumps(result, default=str).encode('utf-8')

        except json.JSONDecodeError:
            request.setResponseCode(400)
            return json.dumps({
                "code": 100,
                "msg": "请求数据格式错误"
            }).encode('utf-8')
        except Exception as e:
            logger.error(f"微信登录处理异常: {e}")
            request.setResponseCode(500)
            return json.dumps({
                "code": 100,
                "msg": "服务器内部错误"
            }).encode('utf-8')


class WeChatTokenVerifyResource(CorsResource):
    """
    微信Token校验资源
    校验微信登录token的有效性
    """
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state

    def render_POST(self, request):
        """
        处理token校验请求
        请求参数: token (待校验的token)
        """
        try:
            # 解析请求体
            content = request.content.read()
            if content:
                data = json.loads(content)
            else:
                data = {}

            # 获取token
            token = data.get('token') or request.args.get(b'token', [None])[0]
            if isinstance(token, bytes):
                token = token.decode('utf-8')

            if not token:
                request.setResponseCode(400)
                return json.dumps({
                    "code": 100,
                    "msg": "缺少token参数"
                }).encode('utf-8')

            # 调用微信认证服务校验token
            result = wechat_auth_service.check_token(token)
            result = tools.dict_snake_case_to_camel(result)

            # 设置响应
            if result.get("code") == 0:
                request.setResponseCode(200)
            else:
                request.setResponseCode(401)

            return json.dumps(result, default=str).encode('utf-8')

        except json.JSONDecodeError:
            request.setResponseCode(400)
            return json.dumps({
                "code": 100,
                "msg": "请求数据格式错误"
            }).encode('utf-8')
        except Exception as e:
            logger.error(f"Token校验处理异常: {e}")
            request.setResponseCode(500)
            return json.dumps({
                "code": 100,
                "msg": "服务器内部错误"
            }).encode('utf-8')


class WeChatLogoutResource(CorsResource):
    """
    微信登出资源
    处理用户登出请求
    """
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state

    def render_POST(self, request):
        """
        处理登出请求
        请求参数: token (待删除的token)
        """
        try:
            # 解析请求体
            content = request.content.read()
            if content:
                data = json.loads(content)
            else:
                data = {}

            # 获取token
            token = data.get('token') or request.args.get(b'token', [None])[0]
            if isinstance(token, bytes):
                token = token.decode('utf-8')

            if not token:
                request.setResponseCode(400)
                return json.dumps({
                    "code": 100,
                    "msg": "缺少token参数"
                }).encode('utf-8')

            # 调用微信认证服务登出
            result = wechat_auth_service.logout(token)

            # 设置响应
            if result.get("code") == 0:
                request.setResponseCode(200)
            else:
                request.setResponseCode(400)

            return json.dumps(result, default=str).encode('utf-8')

        except json.JSONDecodeError:
            request.setResponseCode(400)
            return json.dumps({
                "code": 100,
                "msg": "请求数据格式错误"
            }).encode('utf-8')
        except Exception as e:
            logger.error(f"登出处理异常: {e}")
            request.setResponseCode(500)
            return json.dumps({
                "code": 100,
                "msg": "服务器内部错误"
            }).encode('utf-8')


class WeChatUserInfoResource(CorsResource):
    """
    微信用户信息资源
    根据openid获取用户信息
    """
    isLeaf = True

    def __init__(self, game_state):
        super().__init__()
        self.game_state = game_state

    def render_GET(self, request):
        """
        处理获取用户信息请求
        请求参数: openid (微信用户唯一标识)
        """
        try:
            # 获取openid参数
            openid = request.args.get(b'openid', [None])[0]
            if isinstance(openid, bytes):
                openid = openid.decode('utf-8')

            if not openid:
                request.setResponseCode(400)
                return json.dumps({
                    "code": 100,
                    "msg": "缺少openid参数"
                }).encode('utf-8')

            # 调用微信认证服务获取用户信息
            # 注意：这里需要在wechat_auth_service中添加get_user_by_openid方法
            if hasattr(wechat_auth_service, 'get_user_by_openid'):
                user_info = wechat_auth_service.get_user_by_openid(openid)
                if user_info:
                    result = {
                        "code": 0,
                        "data": {
                            "user_info": user_info
                        }
                    }
                    result = tools.dict_snake_case_to_camel(result)
                    request.setResponseCode(200)
                else:
                    result = {
                        "code": 100,
                        "msg": "未找到用户信息"
                    }
                    request.setResponseCode(404)
            else:
                result = {
                    "code": 100,
                    "msg": "功能未实现"
                }
                request.setResponseCode(501)

            return json.dumps(result, default=str).encode('utf-8')

        except Exception as e:
            logger.error(f"获取用户信息异常: {e}")
            request.setResponseCode(500)
            return json.dumps({
                "code": 100,
                "msg": "服务器内部错误"
            }).encode('utf-8')
